package org.jeecg.cn.edu.scau.vm.common.utils;

import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class RedisIdWorker {
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 开始时间戳(2022-01-01 00:00:00)
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    /**
     * 序列号位数
     */
    private static final long COUNT_BITS = 32;

    /**
     * 生成id
     * @param keyPrefix key前缀
     * @return id
     */
    public String nextId(String keyPrefix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(java.time.ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        //生成序列号
        //获取当前日期
        String date = now.format(java.time.format.DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
        long incr = redisUtil.incr("icr:" + keyPrefix + ":" + date, 1);

        //拼接key(利用位运算)
        //1.时间戳左移32位
        //2.序列号直接或运算（一真则真）
        return String.valueOf(timestamp << COUNT_BITS | incr);
    }
}
